package com.example.datacontact;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	SqlHandler sqlHandler;
	ListView lvCustomList;
	EditText etName, etPhone;
	Button btnsubmit;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);

		lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
		etName = (EditText) findViewById(R.id.et_name);
		etPhone = (EditText) findViewById(R.id.et_phone);
		btnsubmit = (Button) findViewById(R.id.btn_submit);
		
		
		sqlHandler = new SqlHandler(this);
		showlist();
		btnsubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String name = etName.getText().toString();
				String phoneNo = etPhone.getText().toString();
				if(name.length()>0 && phoneNo.length()>0)
				{
					String query = "INSERT INTO PHONE_CONTACTS(name,phone) values ('"
							+ name + "','" + phoneNo + "')";
					sqlHandler.executeQuery(query);
					showlist();
					etName.setText("");
					etPhone.setText("");
				}
				else
				{
					AlertDialog.Builder alertBuilder=new AlertDialog.Builder(MainActivity.this);
					alertBuilder.setTitle("Invalid Data");
					alertBuilder.setMessage("Please, Enter valid data");
					alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});
					alertBuilder.create().show();
				}

			}
		});
		

		lvCustomList.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				ContactListItems contactListItems = (ContactListItems)arg0.getItemAtPosition(arg2);
				final String slno = contactListItems.getSlno();
				final CharSequence[] items = {"Update", "Delete", "Cannel"};
				
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("Make your selection");
				builder.setItems(items, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				         // Do something with the selection
				    	if(items[item]=="Delete")
				    	{
				    		String delQuery = "DELETE FROM PHONE_CONTACTS WHERE slno='"+slno+"' ";	
				    		sqlHandler.executeQuery(delQuery);
				    		Toast.makeText(getApplicationContext(), "Delete success", Toast.LENGTH_LONG).show();
				    		showlist();
				    	}
				    	if(items[item]=="Cannel")
				    	{
				    		dialog.cancel();
				    	}
				    	if(items[item]=="Update")
				    	{
				    		LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
				    		View promptView = layoutInflater.inflate(R.layout.layout_change_data, null);
				    		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				    				MainActivity.this);
				    		alertDialogBuilder.setView(promptView);

				    		final EditText etChangeName = (EditText) promptView
				    				.findViewById(R.id.edtChangeName);
				    		final EditText etChangePhone = (EditText) promptView
				    				.findViewById(R.id.edtChangePhone);				    		
				    		// setup a dialog window
				    		alertDialogBuilder
				    				.setCancelable(false)
				    				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				    					public void onClick(DialogInterface dialog, int id) {
				    						
				    						String upQuery="update PHONE_CONTACTS set name='"+etChangeName.getText()+
				    			    				"', phone='"+etChangePhone.getText()+"' where slno='"+slno+"'";
				    			    		sqlHandler.executeQuery(upQuery);
				    			    		Toast.makeText(getApplicationContext(), "update success", Toast.LENGTH_LONG).show();
				    			    		showlist();
				    					}
				    				})
				    				.setNegativeButton("Cancel",
				    						new DialogInterface.OnClickListener() {
				    							public void onClick(DialogInterface dialog, int id) {
				    								dialog.cancel();
				    							}
				    						});
				    		AlertDialog alert = alertDialogBuilder.create();
				    		alert.show();
				    	}
				    }
				});
				AlertDialog alert = builder.create();
				alert.show();
				showlist();				
			}
		});
	}

	
	
	private void showlist() {

		ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
		contactList.clear();
		String query = "SELECT * FROM PHONE_CONTACTS ";
		Cursor c1 = sqlHandler.selectQuery(query);
		if (c1 != null && c1.getCount() != 0) {
			if (c1.moveToFirst()) {
				do {
					ContactListItems contactListItems = new ContactListItems();
					contactListItems.setSlno(c1.getString(c1
							.getColumnIndex("slno")));
					contactListItems.setName(c1.getString(c1
							.getColumnIndex("name")));
					contactListItems.setPhone(c1.getString(c1
							.getColumnIndex("phone")));
					contactList.add(contactListItems);

				} while (c1.moveToNext());
			}
		}
		c1.close();

		ContactListAdapter contactListAdapter = new ContactListAdapter(
				MainActivity.this, contactList);
		lvCustomList.setAdapter(contactListAdapter);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menuInsert:
			Intent intent= new Intent(getApplicationContext(),ActivityAdd.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
